package com.koron.css2.baseConfig.impl;

import com.github.pagehelper.PageInfo;
import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.mapper.ManageAreaMapper;
import com.koron.css2.baseConfig.queryBean.ManageAreaQueryBean;
import com.koron.css2.baseConfig.vo.ManageAreaVO;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.SelectBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.util.Constant;
import com.koron.util.JsonUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 查询管理区域
 * @author 李攀
 */
public class ManageAreaList implements ServerInterface {
	private static Logger logger = LogManager.getLogger(ManageAreaList.class);

	@Override
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {

		@SuppressWarnings("rawtypes")
		MessageBean<HashMap> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", HashMap.class);
		try {
			List<ManageAreaVO> beans = new ArrayList<ManageAreaVO>();
			ManageAreaMapper mapper = factory.getMapper(ManageAreaMapper.class);
			ManageAreaQueryBean bean = JsonUtils.objectToPojo(req.getData(), ManageAreaQueryBean.class);
			bean.setIsLeaf(-1);//查所有数据
			beans = mapper.findManageArea(bean);
			
			HashMap<String,Object> map = new HashMap<>();
			map.put("pageInfo", new PageInfo<>(beans));
			//找出所有上级目录，显示分级导航
			ArrayList<HashMap<String,String>> navList = new ArrayList<>();
			recParent(mapper, bean.getAreaNo(), navList);
			map.put("navData", navList); 
			info.setCode(Constant.MESSAGE_INT_SUCCESS);
			info.setDescription("success");
			info.setData(map);
		} catch (Exception e) {
			info.setCode(Constant.MESSAGE_DBFAIL);
			info.setDescription("数据库异常");
			logger.error("数据库异常",e);
			factory.close(false);
		}
		return info;
	}
	
	/**
	 * 递归查询每一级目录
	 * @param code
	 * @param sb
	 */
	private void recParent(ManageAreaMapper mapper,String code,ArrayList<HashMap<String,String>> navList) {
		if(code.length()>0){
			SelectBean selb = mapper.findManageAreaByCode(code);
			HashMap<String,String> m = new HashMap<>();
			m.put("code", code);
			m.put("name", selb.getName());
			//存储id和parentId
			m.put("id", selb.getId());
			m.put("parentId", selb.getParentId());
			navList.add(0,m);
			recParent(mapper,code.substring(0, code.length()-5),navList);
		}
	}

}
